package com.luhui.commons.net;

import com.luhui.commons.util.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created with LXD
 *
 * @author:Luhui
 * @qq:729913162
 * @Date:2018-08-22
 * @Time:15:28
 */
public class HttpActive implements WebActive {


    @Override
    public Response get(Request request) throws RequestException{
        try {
            String sendUrl = request.getUrl();
            if(!StringUtils.isBlank(request.getParamStr())){
                sendUrl += "?"+request.getParamStr();
            }
            URL url = new URL(sendUrl);
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            UrlConnectionUtils.setProperty(urlConn,request);
            Response response = UrlConnectionUtils.getResponse(urlConn,request.getCharset());
            return response;
        }catch (IOException e){
            throw new RequestException(e.getMessage(),e);
        }
    }

    @Override
    public Response post(Request request) throws RequestException {
        try {
            String sendUrl = request.getUrl();
            URL url = new URL(sendUrl);
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            UrlConnectionUtils.setProperty(urlConn,request);

            urlConn.setDoOutput(true);
            urlConn.setDoInput(true);
            urlConn.connect();

            PrintWriter out = new PrintWriter(urlConn.getOutputStream());
            out.print(request.getParamStr());
            out.flush();
            out.close();

            Response response = UrlConnectionUtils.getResponse(urlConn,request.getCharset());
            return response;
        }catch (IOException e){
            throw new RequestException(e.getMessage(),e);
        }
    }
}
